<?php if( !defined('BASEPATH'))exit('No direct script access allowed');

/**
 * @author Garry
 * This overwrites the standard AggregatedSimpleXmlElement method addChild to accept an SimpleXmlElement
 *
 */
class AggregatedSimpleXmlElement extends SimpleXMLElement {
	//TODO - Insert your code here
	
	/**
	 * Adds a SimpleXMLElement as child of parent
	 * @see SimpleXMLElement::addChild()
	 */
	public function addChild($obj){
		if(  is_string($obj)){
			$obj = new AggregatedSimpleXmlElement($obj);
		}
		$val = $this->cleanseXMLString((string)$obj->asXML());
		return $this->xmlReplace( $val );
	}
	
	/**
	 * Adds text to simple xml element
	 * @param AggregatedSimpleXMLElement $obj
	 * @param unknown_type $obj
	 * @return AggregatedSimpleXmlElement
	 */
	public function addText($text){
		return $this->xmlReplace( $text );
	}
	/**
	 * worker function to replace content in simple xml element
	 * @param unknown_type $obj
	 * @param unknown_type $val
	 * @return AggregatedSimpleXmlElement
	 */
	protected function xmlReplace( $val ){
		$node = parent::addChild("token");
		$str = (string)$this->asCleanXML();
		// removes the xml declarations
		$replace = $this->cleanseXMLString(str_replace('<token/>', $val, $str));
		$node = new AggregatedSimpleXmlElement((string)$replace);
		return $node;
	}
	/**
	 * cleans the xml of unnecessary mark up 
	 */
	protected function cleanseXMLString($str){
		return "\n".trim(str_replace('<?xml version="1.0"?>','',$str));
	}
	
	public function asCleanXML(){
		return $this->cleanseXMLString($this->asXML());
	}
}

?>